<script setup lang="ts">
import Player from './components/Player.vue'
import WeappPlayer from './components/WeappPlayer.vue'
import Catalog from '@/pages/detail/components/Catalog.vue'
import NavigationBar from './components/TransparentNavigationBar.vue'
import navigateTo from '@/utils/navigator'
import {getPlayUrl} from '@/api/video'

let showPlayer = $ref<boolean>(false) // 控制播放器展示与否
const {videoInfo, currentEpisodeId, init, changeEpisodeId, currentEpisodeTitle, nextEpisode} = $(useVideo())

onLoad(async (options) => {
    // 集id
    const eid = options?.eid
    // 课程id
    const videoId = options?.id
    // 跳转播放页的课程id和存在pinia的课程id不同，需要重新初始化
    if (videoId && Number(videoId) !== videoInfo?.id)
        await init(Number(videoId))

    // 跳转播放页的集id和存在pinia的集id不同，需要更改
    if (eid && Number(eid) !== currentEpisodeId)
        changeEpisodeId(Number(eid))

    // 获取播放地址
    await getPlayerUrl()

    showPlayer = !showPlayer

    // 设置当点击切换集改变集id的监听
    uni.$on('changeEpisodeId', async () => {
        // 兼容h5 url跳转
        // #ifdef H5
        navigateTo(`/pages/player/index?id=${videoInfo!.id}&eid=${currentEpisodeId}`, {
            isHistory: true,
            isNeedLogin: true
        })
        // #endif
        await getPlayerUrl()
    })
})

// 播放地址初始变量
let src = $ref<string>('')

// 请求视频播放地址接口
async function getPlayerUrl() {
    const res = await getPlayUrl({episodeId: currentEpisodeId})
    src = res.data.playResult
}

// 播放自动切换集
async function _nextEpisode() {
    const {base} = useToast()

    const res = await nextEpisode()
    if (!res) {
        base('试看结束，继续观看请购买此课程')
        return
    }

    // #ifdef H5
    navigateTo(`/pages/player/index?id=${videoInfo!.id}&eid=${currentEpisodeId}`, {
        isHistory: true,
        isNeedLogin: true
    })
    // #endif
    await getPlayerUrl()
}

</script>

<template>
    <view flex="~ col">
        <!-- 头部导航栏 -->
        <NavigationBar color="black" :title="currentEpisodeTitle" status-bar-bg="white"/>
        <!-- 视频播放器 -->
        <view w-full flex-shrink-0 absolute>
            <view h-44vh bg-black>
                <!-- #ifdef APP-PLUS -->
                <Player v-if="showPlayer" :src="src" :epsideo-id="currentEpisodeId"
                        @on-player-ended-emitted="_nextEpisode"/>
                <!-- #endif -->
                <!-- #ifdef MP-WEIXIN -->
                <WeappPlayer v-if="showPlayer" :src="src" @on-player-ended-emitted="_nextEpisode"/>
                <!-- #endif -->
            </view>
            <Catalog :play="true"/>
        </view>
    </view>
</template>


